package com.hj.service.impl;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hj.config.StuManException;
import com.hj.dao.StuRoleMapper;
import com.hj.dao.StudentMapper;
import com.hj.form.StuRoleForm;
import com.hj.pojo.StuRole;
import com.hj.pojo.Student;
import com.hj.pojo.StudentExample;
import com.hj.pojo.StudentExample.Criteria;
import com.hj.service.IStudentService;

@Service
public class StudentServiceImpl implements IStudentService {

    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");

    @Autowired
    StudentMapper studentMapper;
    @Autowired
    StuRoleMapper stuRoleMapper;

    @Override
    public PageInfo<Student> list(Integer page, Integer size) {
    	PageHelper.startPage(page, size);
        return new PageInfo<>(studentMapper.selectByExample(null));
    }

    @Override
    public void add(Student student) {
    	
    	if (StringUtils.isEmpty(student.getsName())) {
			throw new StuManException("请输入用户名");
		}
    	
    	if (StringUtils.isEmpty(student.getsPassword())) {
    		throw new StuManException("请输入密码");
    	}
    	
    	if (student.getsName().length() > 20) {
    		throw new StuManException("用户名过长");
    	}
        
    	student.setsId(sdf.format(new Date()));
        studentMapper.insert(student);
    }

    @Override
    public void delete(String id) {
        studentMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void update(Student student) {
        studentMapper.updateByPrimaryKeySelective(student);
    }

    @Override
    public Student findOne(String id) {
        return studentMapper.selectByPrimaryKey(id);
    }

	@Override
	public void addRoles(StuRoleForm stuRole) {
		
		for (Integer rid: stuRole.getRids()) {
			StuRole sr = new StuRole();
			sr.setSid(stuRole.getSid());
			sr.setRid(rid);
			stuRoleMapper.insertSelective(sr);
		}
		
	}

	@Override
	public Student login(String uname, String passwd) {
		
		StudentExample ex = new StudentExample();
		Criteria criteria = ex.createCriteria();
		criteria.andSNameEqualTo(uname);
		List<Student> list = studentMapper.selectByExample(ex );
		
		if (list.size() == 0) {
			throw new StuManException("用户不存在");
		}
		
		Student student = list.get(0);
		if (!student.getsPassword().equals(passwd)) {
			throw new StuManException("密码错误");
		}
		
		return student;
	}
}
